<?php
/**
 * 后台管理首页控制器
 *
 */

class SiteController extends MyController
{
	public function init()
	{
		parent::init();
	}

	public function actionIndex()
	{
		$data = array();
		$data['name'] = Yii::app()->user->getState('name');
		$this->pageTitle = SITENAME.'数据控制后台';
		$this->render('/site/index', $data);
	}

	public function actionLogin()
	{
		$msg = '';
		$this->pageTitle = SITENAME.'数据控制后台--登录';
		if(Yii::app()->request->requestType == 'POST')
		{
			$username = trim( Yii::app()->request->getParam('username'));
			$password = Yii::app()->request->getParam('password');
			$verifyCode = trim(strtolower(Yii::app()->request->getParam('verifyCode')));
			if($verifyCode == strtolower(Yii::app()->user->getState('re_code')))
			{
				Yii::app()->user->setState('re_code','');
				if($username == '' || $password == '')
				{
					$this->showLogin('用户名或密码为能为空。');
				}

				// 使用提供的用户名和密码登录用户
				$identity = new MyUserIdentity($username, $password);
				
				if($identity->admin_authenticate())
				{
					Yii::app()->user->login($identity,3600);
					$this->redirect('/site/index');
				}
				else
				{
					$this->showLogin('用户名或密码错误。');
				}
			}
			else
			{
				Yii::app()->user->setState('re_code','');
				$this->showLogin('验证码错误。');
			}
		}
		else
		{
			//已经登陆跳转到首页
			if(!Yii::app()->user->isGuest && Yii::app()->user->getState('admin_is_login'))
			{
				$this->redirect('/site/index');
			}
			else
			{
				//显示登陆界面
				$this->showLogin();
			}
		}
	}
	
	private function showLogin($msg='请登录')
	{
		$this->renderPartial('login',array('msg'=>$msg));
		exit;
	}
	
	/**
	 * 
	 * 输出验证码
	 */
	public function actionSeccode()
	{
		echo MySecCode::show();
	}
	/**
	 * 
	 * 公用的上传文件方法。
	 */
	public function actionUploadimg()
	{
		$inputName='filedata';//表单文件域name
		$baseDir= Yii::app()->params['imgpath'];//上传文件保存路径，结尾不要带/
		$maxAttachSize=4000000;//最大上传大小，默认是4M
		$upExt='jpg,jpeg,gif,png';//上传扩展名
		$baseURL = Yii::app()->params['imgdomain'];
		$msg = "";
		$tempPath=$baseDir.'/'.date("YmdHis").mt_rand(10000,99999).'.tmp';
		$localName='';
		
		if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){//HTML5上传
			file_put_contents($tempPath,file_get_contents("php://input"));
			$localName=urldecode($info[2]);
		}
		else{//标准表单式上传
			$upfile=@$_FILES[$inputName];
			if(!isset($upfile)) $this->uploadend('文件域的name错误');
			elseif(!empty($upfile['error'])){
				switch($upfile['error'])
				{
					case '1':
						$this->uploadend('文件大小超过了php.ini定义的upload_max_filesize值');
						break;
					case '2':
						$this->uploadend('文件大小超过了HTML定义的MAX_FILE_SIZE值');
						break;
					case '3':
						$this->uploadend('文件上传不完全');
						break;
					case '4':
						$this->uploadend('无文件上传');
						break;
					case '6':
						$this->uploadend('缺少临时文件夹');
						break;
					case '7':
						$this->uploadend('写文件失败');
						break;
					case '8':
						$this->uploadend('上传被其它扩展中断');
						break;
					case '999':
					default:
						$this->uploadend('无有效错误代码');
				}
			}
			elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')$this->uploadend('无文件上传');
			else{
				move_uploaded_file($upfile['tmp_name'],$tempPath);
				$localName=$upfile['name'];
			}
		}
		$fileInfo=pathinfo($localName);
		$extension=$fileInfo['extension'];
		if(preg_match('/'.str_replace(',','|',$upExt).'/i',$extension))
		{
			$bytes=filesize($tempPath);
			if($bytes > $maxAttachSize) $this->uploadend('请不要上传大小超过'.formatBytes($maxAttachSize).'的文件');
			$attachDir = $baseDir.'/day_'.date('ymd');
			if(!is_dir($attachDir))
			{
				@mkdir($attachDir, 0755);
				@fclose(fopen($attachDir.'/index.html', 'w'));
			}
			$newFilename=date("His").str_replace(' ', '', $localName);
			$targetPath = $attachDir.'/'.$newFilename;
			
			rename($tempPath,$targetPath);
			@chmod($targetPath,0644);
			$msg = str_replace($baseDir, $baseURL, $targetPath);
		}
		else $this->uploadend('上传文件扩展名必需为：'.$upExt);
		
		@unlink($tempPath);
		$this->uploadend('',$msg);
	}
	
	private function uploadend($err,$msg='')
	{
		die(json_encode(array('err'=>$err,'msg'=>$msg)));
	}
}